package com.devtools.generator.service;

import com.devtools.generator.properties.DevtoolsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取数据库所有的表
 *
 * @author zhangyu
 * @date 2020-01-14
 */
@Slf4j
@EnableConfigurationProperties(DevtoolsProperties.class)
@Service
public class TableService {

    @Resource
    private DevtoolsProperties devtoolsProperties;
    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取当前数据库所有的表信息
     */
    public List<Map<String, Object>> getAllTables() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<String> dbNames = devtoolsProperties.getDbNames();
        if (!CollectionUtils.isEmpty(dbNames)) {
            dbNames.forEach(db -> {
                String sql = "select TABLE_NAME as tableName,TABLE_COMMENT as tableComment from information_schema.`TABLES` where TABLE_SCHEMA = '" + db + "'";
                Map<String, Object> map = new HashMap<>();
                map.put("db", db);
                map.put("list", jdbcTemplate.queryForList(sql));
                list.add(map);
            });
        }
        return list;
    }

}
